#!/bin/bash

NET_CLS_DIR="/sys/fs/cgroup/net_cls/tproxy"
NET_CLS_ID=1088
PKT_MARK=1088
TCP_PORT=1088
UDP_PORT=1088

function init() {
    # CGroup
    mkdir -p ${NET_CLS_DIR}
    chmod 0666 ${NET_CLS_DIR}/cgroup.procs
    echo ${NET_CLS_ID} > ${NET_CLS_DIR}/net_cls.classid

    # IPv4
    iptables -t mangle -A PREROUTING -m mark ! --mark ${PKT_MARK} -j RETURN
    iptables -t mangle -A PREROUTING -p tcp -j TPROXY --on-port ${TCP_PORT}
    iptables -t mangle -A PREROUTING -p udp -j TPROXY --on-port ${UDP_PORT}
    iptables -t mangle -A OUTPUT -m cgroup --cgroup ${NET_CLS_ID} -j MARK --set-mark ${PKT_MARK}

    ip rule add fwmark ${PKT_MARK} table 100
    ip route add local default dev lo table 100

    # IPv6
    ip6tables -t mangle -A PREROUTING -m mark ! --mark ${PKT_MARK} -j RETURN
    ip6tables -t mangle -A PREROUTING -p tcp -j TPROXY --on-port ${TCP_PORT}
    ip6tables -t mangle -A PREROUTING -p udp -j TPROXY --on-port ${UDP_PORT}
    ip6tables -t mangle -A OUTPUT -m cgroup --cgroup ${NET_CLS_ID} -j MARK --set-mark ${PKT_MARK}

    ip -6 rule add fwmark ${PKT_MARK} table 100
    ip -6 route add local default dev lo table 100

    echo $$ > ${NET_CLS_DIR}/cgroup.procs
}

if [ ! -e ${NET_CLS_DIR} ]; then
    init > /dev/null 2> /dev/null
fi

echo $$ > ${NET_CLS_DIR}/cgroup.procs
exec "$@"
